<?php
namespace app\common\library\xilujob\resume;


use app\common\library\xilujob\ResumeLibrary;
use app\common\model\xilujob\Resume;
use app\common\model\xilujob\ResumePersonalInfo;
use app\common\model\xilujob\WorkExperience;

class PersonalInfo extends BaseModule {

    protected $name = ResumeLibrary::MODULE_PERSONAL_INFO;

    public function onCreateResume(Resume $resume) {
        $personalInfo = new ResumePersonalInfo(['user_id'=>$resume->user_id, 'resume_id'=>$resume->id,'avatar'=>$resume->user->avatar]);
        $ret = $personalInfo->save();
        if(!$ret) {
            throw new ModuleException($personalInfo->getError());
        }
    }

    public function add($data) {
        throw new ModuleException("Module '{$this->name}' does not support add method");
    }

    public function del($id) {
        throw new ModuleException("Module '{$this->name}' does not support del method");
    }

    /**
     * 获取所有字段的key
     */
    protected function keys() {
        return ['avatar','realname','gender','birthdate','education_level_id','work_experience_id','hukou_city','current_state_id','email','mobile','marital'];
    }

    /**
     * 获取验证规则
     * @return array
     */
    protected function getRules() {
        return [
            'realname' => 'length:1,20',
            'gender' => 'in:0,1,2',
            'birthdate' => 'dateFormat:Y-m-d',
            'hukou_city' => 'length:1,50',
            'email' => 'email',
            'marital' => 'in:0,1,2',
            'mobile' => 'regex:^1[3456789]\d{9}$',
            'work_experience_id' => function($value, $data) {
                if($value==0) {
                    return true;
                }
                $value = intval($value);
                if($value<1)
                    return '工作经验选择错误';
                $count = WorkExperience::where('id',$value)->count();
                if($count<1)
                    return '工作经验选择错误';
                return true;
            },
        ];
    }

    /**
     * 获得Model实例
     */
    protected function getModel() {
        return new ResumePersonalInfo();
    }

    /**
     * @return array score: 当前分数， max: 满分
     */
    public function getCompleteScore() {
        $personalInfo = $this->getModel()->where('resume_id', $this->resume->id)->find();
        $total = $complete = 0;
        foreach ($this->keys() as $key) {
            if($key==='idcard_no')
                continue;
            $total++;
            if($personalInfo->$key) {
                $complete++;
            }
        }
        // 整个模块基础分20
        $complete = $complete / $total * 20;
        $total = 20;

        return ['score'=>$complete, 'max'=>$total];
    }

}